<template>
    <div>
        <h3>我的文章列表</h3>
        <ul>
            <li v-for="item in articleList" :key="item.id">
                {{ item.title }} -
                <button @click="handleEdit(item.id)">编辑</button>
                <form v-if="currentArticle && currentArticle.id == item.id">
                    <input type="text" v-model="currentArticle.title" placeholder="文章标题" required>
                    <br>
                    <textarea v-model="currentArticle.content" placeholder="文章内容" required></textarea>
                    <br>
                    <input type="text" v-model="currentArticle.intro" placeholder="文章引子" required>
                    <br>
                    <input type="text" v-model="currentArticle.read" placeholder="文章阅读量" required>
                    <br>
                    <input type="text" v-model="currentArticle.like" placeholder="文章喜欢" required>
                    <br>
                    <input type="text" v-model="currentArticle.view" placeholder="文章评论" required>
                    <br>
                    <select v-model="currentArticle.category_id">
                        <option value="1">首页</option>
                        <option value="2">博文</option>
                        <option value="3">视频</option>
                        <option value="4">下载</option>
                        <option value="5">行业动态</option>
                        <option value="6">干货分享</option>
                        <option value="7">课程</option>
                        <option value="8">店铺</option>
                    </select>
                    <br>
                    <el-select v-model="currentArticle.tags" multiple plsaceholder="请选择标签" style="width: 100%;"
                        filterable :options="allTags" :key="item.id" :disabled="!currentArticle">
                        <el-option v-for="tag in allTags" :key="tag.id" :laber="tag.title" :value="tag.id"></el-option>
                    </el-select>
                    <br>
                    <button @click="handleUpdate">保存修改</button>
                    <br>
                </form>

                <button @click="handleDelete(item.id)">删除</button>
            </li>
        </ul>
    </div>
    <div>
        <button @click="toggleCreateForm">创建文章</button>

        <form v-if="isCreate" @submit.prevent="handleCreate">
            <input type="text" v-model="newArticle.title" placeholder="文章标题" required>
            <br>
            <textarea v-model="newArticle.content" placeholder="文章内容" required></textarea>
            <br>
            <input type="text" v-model="newArticle.intro" placeholder="文章引子" required>
            <br>
            <input type="text" v-model="newArticle.read" placeholder="文章阅读量" required>
            <br>
            <input type="text" v-model="newArticle.like" placeholder="文章喜欢" required>
            <br>
            <input type="text" v-model="newArticle.view" placeholder="文章评论" required>
            <br>
            <select v-model="newArticle.category_id">
                <option value="1">首页</option>
                <option value="2">博文</option>
                <option value="3">视频</option>
                <option value="4">下载</option>
                <option value="5">行业动态</option>
                <option value="6">干货分享</option>
                <option value="7">课程</option>
                <option value="8">店铺</option>
            </select>
            <br>
            <el-select v-model="newArticle.tags" multiple placeholder="请选择标签（支持搜索）" style="width: 100%;" filterable
                :options="allTags">
                <el-option v-for="tag in allTags" :key="tag.id" :label="tag.title" :value="tag.id"></el-option>
            </el-select>
            <br>
            <button type="submit">是否创建文章</button>
        </form>
    </div>
</template>
<script setup>
import request from '@/request';
import { ref, reactive, onMounted } from 'vue';
import { ElMessage } from 'element-plus'

const isCreate = ref(false)
const isUpdate = ref(false)
const currentArticle = ref(null)
const articleList = ref([])
const newArticle = ref({
    title: '',
    content: '',
    intro: '',
    category_id: '',
    read: '',
    like: '',
    view: '',
    tags: []
})
const allTags = ref([]);
onMounted(() => {
    fetchArticles()
    fetchTags()
})
//获取所有标签
const fetchTags = () => {
  request({
    url: '/addtag/',
    method: 'get'
  }).then(response => {
    if (response.status == 200) {
      allTags.value = response.data.tags; 
    } else {
      ElMessage.error('加载标签失败');
    }
  }).catch(error => {
    ElMessage.error('加载标签失败');
  });
};

function fetchArticles() {
    request({
        url: '/article/',
        method: 'get'
    }).then(response => {
        if (response.status == 200) {
            articleList.value = response.data.article_list;
            ElMessage.success('文章获取成功')
        }
    }).catch(error => {
        ElMessage.error(error)
    })
}
//切换创建表单显示
function toggleCreateForm() {
    isCreate.value = !isCreate.value;
    if (!isCreate.value) {
        resetNewArticle(); // 隐藏时重置表单
    }
}
//重置
function resetNewArticle() {
    newArticle.value = {
        title: '',
        content: '',
        intro: '',
        category_id: '',
        read: '',
        like: '',
        view: '',
        tags: []
    }
}
//创建文章
function handleCreate() {
    const formData = {
        title: newArticle.value.title,
        content: newArticle.value.content,
        intro: newArticle.value.intro,
        category_id: parseInt(newArticle.value.category_id),
        read: parseFloat(newArticle.value.read),
        like: parseInt(newArticle.value.like),
        view: parseInt(newArticle.value.view),
        tags: newArticle.value.tags
    }
    request({
        url: '/article/',
        method: 'post',
        data: formData
    }).then(response => {
        if (response.status == 201) {
            isCreate.value = !isCreate.value
            resetNewArticle()
            fetchArticles()
            ElMessage.success('文章创建成功')
        }
    }).catch(error => {
        ElMessage.error('创建文章失败' + error.message)
    })
}
//编辑文字
function handleEdit(articleId) {
    isUpdate.value = !isUpdate.value
    request({
        url: `/article/${articleId}/`,
        method: 'get',
    }).then(response => {
        if (response.status == 200) {
            const { id, title, intro, content, category_id, read, like, view, tags } = response.data.article;
            currentArticle.value = {
                id,
                title,
                intro,
                content,
                category_id: String(category_id),
                read: String(read),
                like: String(like),
                view: String(view),
                tags: tags || []
            };
            ElMessage.success('获取成功')
        }
    }).catch(error => {
        isUpdate.value = !isUpdate.value
        ElMessage.error('加载编辑数据失败' + error.message)
    })
}
//更新文章
function handleUpdate() {
    const formData = {
        title: currentArticle.value.title,
        content: currentArticle.value.content,
        intro: currentArticle.value.intro,
        category_id: parseInt(currentArticle.value.category_id),
        read: parseFloat(currentArticle.value.read),
        like: parseInt(currentArticle.value.like),
        view: parseInt(currentArticle.value.view),
        tags: currentArticle.value.tags
    };
    request({
        url: `/article/${currentArticle.value.id}/`,
        method: 'put',
        data: formData
    }).then(response => {
        if (response.status == 200) {
            isUpdate.value = !isUpdate.value
            currentArticle.value = null
            fetchArticles()
            ElMessage.success('修改成功')
        }
    }).catch(error => {
        ElMessage.error('修改失败' + error.message)
    })
}
function handleDelete(articleId) {
    if (confirm('确认删除此文章?')) {
        request({
            url: `/articles/${articleId}/`,
            method: 'delete'
        }).then(response => {
            if (response.status == 200) {
                ElMessage.success('删除成功')
                fetchArticles()
            }
        }).catch(error => {
            ElMessage.error('删除失败' + error.message)
        })
    }
}
</script>
<style scoped>
li {
    margin-bottom: 1rem;
    padding: 0.5rem;
    border: 1px solid #e5e7eb;
    border-radius: 4px;
}

form {
    margin-top: 0.5rem;
}

input,
textarea,
select {
    margin: 0.3rem 0;
    padding: 0.4rem;
    width: 100%;
    box-sizing: border-box;
}

button {
    background-color: #b5cdee;
    color: white;
    padding: 0.4rem 0.8rem;
    border: none;
    border-radius: 4px;
    cursor: pointer;
}

button:hover {
    background-color: #5884eb;
}
</style>